import WebSocket, { WebSocketServer } from 'ws'
import modules from '../db/schema/index.js'
const { Order } = modules
import conf from '../conf.js'

const { wsPort } = conf
const WS = new WebSocketServer({ port: wsPort })

WS.on('connection', function (ws) {
  // 客户端连接时才run this

  // 接受消息
  ws.on('message', function (message) {
    console.log(`[SERVER] Received:${message}`)
  })

  const wsSuccess = (data, message = '您有一条新消息啦') => JSON.stringify({ code: 0, message, data })
  // 监听 Order表更新
  Order.watch().on('change', async data => {
    console.log(new Date(), data)
    const count = await Order.countDocuments()
    // 推送消息
    ws.send(wsSuccess(count, '订单量有更新'))
  })
})
